import { createReducer } from 'reduxsauce'
import { REHYDRATE } from 'redux-persist/es/constants'
import {
  INIT_USER,
  UPDATE_USER_BY_WECHAT_INFO,
  UPDATE_PROFILE,
  UPDATE_PROFILE_AVATAR,
  GET_PROFILE, SET_ACQUIRE_CHANNEL
} from '@ACTIONS/profile'
import {
  LOGOUT_USER,
  LOGIN_WEIXIN,
  VISITOR_LOGIN,
  LOGIN_OR_REGISTER_BY_PHONE,
  WECHAT_LOGIN
} from '@ACTIONS/auth'
import { USER_STATUS } from '@CONSTANTS/profile'
import { ProfileStateITF } from '@REDUXITF/profile'

const INITIAL_STATE: ProfileStateITF = {
  user: null,
  isVisitor: true,
  acquireChannel: ''
}

const rehydrate = (state: ProfileStateITF, { payload }: { payload: { profile: ProfileStateITF }}) => {
  if (payload && payload.profile) {
    return { ...INITIAL_STATE, ...payload.profile }
  }
  return { ...state }
}

export default createReducer(INITIAL_STATE, {
  [REHYDRATE]: rehydrate,
  [INIT_USER.REQUEST]: (state, { user: { Status, AcquireChannel }, user }) => ({
    ...state,
    user,
    isVisitor: Status === USER_STATUS.Tentative,
    acquireChannel: AcquireChannel
  }),
  [LOGIN_WEIXIN.SUCCESS]: (state, { result }) => ({ ...state, user: result, isVisitor: false }),

  [LOGIN_OR_REGISTER_BY_PHONE.SUCCESS]: (state, { result }) => ({ ...state, user: result, isVisitor: false }),

  [WECHAT_LOGIN.SUCCESS]: (state, { user }) => ({ ...state, user, isVisitor: false }),

  [VISITOR_LOGIN.SUCCESS]: (state, { user }) => ({ ...state, isVisitor: true, user }),

  [LOGOUT_USER.SUCCESS]: state => ({ ...state, user: null, isVisitor: true }),

  [UPDATE_USER_BY_WECHAT_INFO.SUCCESS]: (state, { data }) => ({
    ...state,
    user: data,
    isVisitor: false,
  }),

  [UPDATE_PROFILE.SUCCESS]: (state, { data }) => ({
    ...state,
    user: data,
    isVisitor: false,
  }),
  [GET_PROFILE.SUCCESS]: (state, { data }) => ({
    ...state,
    user: data,
    isVisitor: false,
  }),

  [UPDATE_PROFILE_AVATAR.SUCCESS]: (state, { NewAvatarVersion }) => ({
    ...state,
    user: {
      ...state.user,
      AvatarVersion: NewAvatarVersion,
    },
  }),
  [SET_ACQUIRE_CHANNEL.REQUEST]: (state, { acquireChannel }) => ({
    ...state,
    acquireChannel
  }),
})
